/**
 * 供应商-订单管理 <br/>
 *
 * @author fsl-gongl-20151029
 *
 */
$(function () {

    var defaultPagingObj = {
        total : 0,
        pageSize : 0,
        page : 0
    };

    PAGE_DATA.pagingObj = $.extend(defaultPagingObj, PAGE_DATA.pagingObj);

    // 主要分类：咖啡豆及咖啡相关,等.
    commTemplUtil.initPage();

    // 渲染左侧菜单;
    commTemplUtil.initCommLeftMemu();
    commTemplUtil.setLeftMenu(4);

    $("#commTabs_1").commNavTabs();

    // 页面首次 渲染.
    renderPage();

});

/**
 * 页面初始化时, 渲染 订单列表.<br/>
 *
 * @author fsl-gongl-20151102
 *
 */
function renderPage() {

    var listData = PAGE_DATA.orderListData.data || [];
    renderTabs(listData);

    // 时间-jquery-UI.
    $(".sel-order-time-1").datepicker();
    $(".sel-order-time-2").datepicker();

    // 搜索
    $(".sel-search-btn").each(function () {
        $(this).on("click", function () {
            getOrderListData(1, $(this).parents(".body-item"));
        });
    });

};

/**
 * 渲染所有tab.
 *
 */
function renderTabs(listData) {

    var orderTempl = _.template($("#order-templ").html());

    var onClickObj = {};

    // 初始化各tab内容.
    for (var i = 0, len = listData.length; i < len; i++) {

        onClickObj = {
            onClick : function () {
                var clickPage = $(this).attr("data-page");

                var tabObj = $(this).parents(".body-item");

                getOrderListData(parseInt(clickPage), tabObj);
            }
        };

        renderOrderList("#order-list-body-" + i,
            listData[i].detail || [],
            orderTempl);

        var tmpConf = $.extend(listData[i].pagingObj || {}, onClickObj);
        commTemplUtil.initPaging("#comm-paging-" + i, tmpConf);
    }
};

/**
 * 渲染订单<br/>
 *
 * @param containerId {string} 包含订单的容器标签<br/>
 * @param data {array} 订单列表数据.
 * @param templ {object} 订单模板
 *
 * @author fsl-gong-20151029
 *
 */
function renderOrderList(containerId, data, templ) {

    var tmpHtml = templ(data);
    var containObj = $(containerId).find(".container");
    containObj.html(tmpHtml);

    // 绑定事件-弹出框
    var modifyTempl = _.template($("#modify-total-templ").html());

    var modifyDefData = {
        buyerName : "",
        orderNo : "",
        goodsTotalPrice : "",
        distributePrice : "",
        orderPrice : ""
    };
    // 调整费用
    containObj.find(".sel-modify-total-btn").on("click", function () {

        // order-id="100001"
        var orderIdVal = $(this).parent().attr("order-id") || "";

        $.ajax({
            url : PAGE_CONFIG.requestUrl.getOrderInfoS4,
            type : "get",
            data : {
                orderNo : orderIdVal
            },
            success : function (result) {

                var orderData = $.extend(modifyDefData, result.data);

                // 调整费用-弹出框。
                var diaModify = dialog({
                        title : '调整费用',
                        width : 420,
                        content : modifyTempl(orderData),
                        onshow : function () {

                            var that = this;
                            var dialogId = this.id;
                            // id="content:1446531230762"
                            var dialogObj = $("[id='content:" + dialogId + "']");

                            // 验证规则;
                            var valiForm = dialogObj.find("form").validate({
                                    rules : {
                                        goodsTotalPrice : {
                                            required : true,
                                            number : true
                                        },
                                        distributePrice : {
                                            required : true,
                                            number : true
                                        }
                                    }
                                });

                            // 重新计算 订单总价
                            dialogObj.find("input[name='goodsTotalPrice'], input[name='distributePrice']").on("blur", function () {

                                var price1 = dialogObj.find("input[name='goodsTotalPrice']").val();
                                var price2 = dialogObj.find("input[name='distributePrice']").val();

                                price1 = parseInt(price1) || 0;
                                price2 = parseInt(price2) || 0;

                                var priceTotal = price1 + price2;
                                dialogObj.find("label[role='orderPriceLabel']").html(priceTotal);
                                dialogObj.find("input[name='orderPrice']").val(priceTotal);

                            });

                            // 取消
                            dialogObj.find(".sel-cancel-btn").on("click", function () {
                                that.remove();
                            });

                            // 提交
                            dialogObj.find(".sel-submit-btn").on("click", function () {

                                if (valiForm.form()) {

                                    // 输入验证 合法
                                    var orderNoVal = dialogObj.find(".sel-order-num").html() || '';
                                    var goodsTotalPriceVal = dialogObj.find("input[name='goodsTotalPrice']").val() || '';
                                    var distributePriceVal = dialogObj.find("input[name='distributePrice']").val() || '';
                                    var orderPriceVal = dialogObj.find("input[name='orderPrice']").val() || '';

                                    $.ajax({
                                        url : PAGE_CONFIG.requestUrl.updateOrderInfoS4,
                                        type : "put",
                                        data : {
                                            orderNo : orderNoVal,
                                            goodsTotalPrice : goodsTotalPriceVal,
                                            distributePrice : distributePriceVal,
                                            orderPrice : orderPriceVal,
                                            _token : COMM_DATA.csrfToken
                                        },
                                        success : function (result) {
                                            
                                            // TODO, var listData = PAGE_DATA.orderListData.data || [];
                                            var listData = result.data || [];
                                            renderTabs(listData);

                                            that.remove();
                                        },
                                        error : function (result) {
                                            
                                            that.remove();
                                            
                                            commTemplUtil.showErrorDialog({
                                                title : '注意！',
                                                message : '调整费用更新失败！',
                                                ok_txt : "确定"
                                            });

                                        },
                                    });

                                }

                            });
                        }
                    });
                diaModify.showModal();
            },
            error : function (result) {
                commTemplUtil.showErrorDialog({
                    title : "注意！",
                    message : "调整费用-获取数据失败！",
                    ok_txt : "确定"
                });
            }
        });

    });
    
    //  TODO, 取消订单
    containObj.find(".sel-cacel-btn").on("click", function () {
        var orderIdVal = $(this).parent().attr("order-id") || "";

        $.ajax({
            url : PAGE_CONFIG.requestUrl.deleteOrderInfoS4,
            type : "delete",
            data : {
                orderNo : orderIdVal,
                _token: COMM_DATA.csrfToken
            },
            success : function (result) {
                // TODO,  PAGE_DATA.orderListData.data
                var listData = $.extend([], result.data);
                renderTabs(listData);
            },
            error : function (result) {
                
                commTemplUtil.showErrorDialog({
                    title : '注意！',
                    message : '取消订单 失败！',
                    ok_txt : "确定"
                });
            }
        });
    });
    
    var logisticTempl = _.template($("#logistic-templ").html());
    
    var defLogisticData = {
        orderNo : '',
        distributeWay : '',
        logisticNo : ''
    };
    
    // 发货
    containObj.find(".sel-send-btn").on("click", function () {

        var orderIdVal = $(this).parent().attr("order-id") || "";

        var logisticData = $.extend(defLogisticData, {
                orderNo : orderIdVal
            });

        var diaLogistic = dialog({
                title : '发货',
                width : 420,
                content : logisticTempl(logisticData),
                onshow : function () {

                    var that = this;
                    var dialogId = this.id;
                    // id="content:1446531230762"
                    var dialogObj = $("[id='content:" + dialogId + "']");
                    
                    renderLogistic(dialogObj, that);
                }

            });
        diaLogistic.showModal();
    });
    
    // 修改单号
    containObj.find(".sel-modify-order-btn").on("click", function () {
        
        var orderIdVal = $(this).parent().attr("order-id") || "";
        
        $.ajax({
            url : PAGE_CONFIG.requestUrl.getOrderLogisticInfoS4,
            type : "get",
            data : {
                orderNo : orderIdVal
            },
            success : function (result) {

                var logisticData = $.extend(defLogisticData, result.data);

                var diaUpdLogistic = dialog({
                        title : '发货',
                        width : 420,
                        content : logisticTempl(logisticData),
                        onshow : function () {
                            var that = this;
                            var dialogId = this.id;
                            // id="content:1446531230762"
                            var dialogObj = $("[id='content:" + dialogId + "']");
                            
                            renderLogistic(dialogObj, that);
                    
                        }

                    });
                diaUpdLogistic.showModal();
            },
            error : function (result) {
                commTemplUtil.showErrorDialog({
                    title : "注意！",
                    message : "发货-获取数据失败！",
                    ok_txt : "确定"
                });
            }
        });

    });
};

/**
 * 渲染 "发货"弹出框. <br/>
 * 
 */
function renderLogistic(dialogObj, diaContext) {
    
    // 验证规则;
    var valiForm = dialogObj.find("form").validate({
            rules : {
                distributeWay : {
                    required : true
                },
                logisticNo : {
                    required : true
                }
            }
        });
    
    // 取消
    dialogObj.find(".sel-cancel-btn").on("click", function () {
        diaContext.remove();
    });
    
    // 提交
    dialogObj.find(".sel-submit-btn").on("click", function () {

        if (valiForm.form()) {

            // 订单号
            var orderNoVal = dialogObj.find("input[name='orderNo']").val() || '';
            // 配送方式
            var distributeWayVal = dialogObj.find("input[name='distributeWay']").val() || '';
            // 物流单号
            var logisticNoVal = dialogObj.find("input[name='logisticNo']").val() || '';

            // 提交物流信息.
            $.ajax({
                url : PAGE_CONFIG.requestUrl.UpdateOrderLogisticInfoS4,
                type : "put",
                data : {
                    orderNo : orderNoVal,
                    distributeWay : distributeWayVal,
                    logisticNo : logisticNoVal,
                    _token : COMM_DATA.csrfToken,
                },
                success : function (result) {

                    diaContext.remove();
                     // TODO, var listData = PAGE_DATA.orderListData.data || [];
                    var listData = result.data || [];
                    renderTabs(listData);
                },
                error : function (result) {

                    diaContext.remove();

                    commTemplUtil.showErrorDialog({
                        title : "注意！",
                        message : "发货-提交数据失败！",
                        ok_txt : "确定"
                    });
                }
            });
        }

    });
    
};

/**
 * 获取订单数据.<br/>
 *
 * @param page {int} 页码<br/>
 * @param tab {object} 当前 tab 对象.
 * //@param templ {object} 订单模板
 *
 * @author fsl-gong-20151029
 *
 */
function getOrderListData(page, tab) {

    var orderTempl = _.template($("#order-templ").html());
    var status = tab.find(".sel-status").val() || "";
    var orderVal = tab.find(".sel-order-serial").val() || "";
    var time1 = tab.find(".sel-order-time-1").val() || "";
    var time2 = tab.find(".sel-order-time-2").val() || "";
    var name = tab.find(".sel-buyer-name").val() || "";

    if (!(time1 == "" || time2 == "")) {
        // 只有输入两个时间 才需要判断 时间合法性.
        var chkFlag = commTemplUtil.checkDate(time1, time2);

        if (!chkFlag) {
            // 不合法--date1 > date2
            commTemplUtil.showErrorDialog({
                title : "注意",
                message : "请检查时间先后顺序!",
                ok_txt : "确定"
            });
            return false;
        }
    }

    $.ajax({
        url : PAGE_CONFIG.requestUrl.getOrderListS4,
        type : "get",
        data : {
            page : page,
            pageSize : PAGE_DATA.pagingObj.pageSize || 10,
            tab : status,
            orderId : orderVal,
            startTime : time1,
            endTime : time2,
            buyerName : name
        },
        success : function (result) {
            var listData = $.extend([], result.data);

            onClickObj = {
                onClick : function () {
                    var clickPage = $(this).attr("data-page");

                    var tabObj = $(this).parents(".body-item");

                    getOrderListData(parseInt(clickPage), tabObj);
                }
            };

            renderOrderList("#" + tab.attr("id"),
                listData || [],
                orderTempl);

            var tmpConf = $.extend(result.pagingConfData || {}, onClickObj);
            commTemplUtil.initPaging("#" + tab.find(".comm-paging").attr("id"), tmpConf);

        },
        error : function () {
            commTemplUtil.showErrorDialog({
                title : '注意！',
                message : '获取订单数据失败！',
                ok_txt : "确定"
            });

            renderOrderList("#" + tab.attr("id"), [], orderTempl);
            commTemplUtil.initPaging("#" + tab.find(".comm-paging").attr("id"), {});
        }
    });
};

